package com.douwan.ap;

import java.util.List;


import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.SystemClock;
import android.util.Log;

public class Wifi {
	public WifiManager wifiManager = null;
	private List<ScanResult> wifi_list = null;
	private List<WifiConfiguration> existingConfigs = null;
	private long old_time = 0;
	
	public Wifi(Context context)
	{
		wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
		wifiManager.getConnectionInfo();
	}
	
	public void openWifi()
	{
			if(!wifiManager.isWifiEnabled())
			{
				wifiManager.setWifiEnabled(true);
				Log.i("debug.info","open WIFI...");
			}
		
	}
	
	public void closeWifi()
	{
		if(wifiManager.isWifiEnabled())
		{
			wifiManager.setWifiEnabled(false);
			Log.i("debug.info","close WIFI...");
		}
	}
	
	public String checkWifiState()
	{
		String result = null;
		switch (wifiManager.getWifiState()) {
		case WifiManager.WIFI_STATE_ENABLED:
			result = "WIFI_STATE_ENABLED";
			break;
		case WifiManager.WIFI_STATE_DISABLED:
			result = "WIFI_STATE_DISABLED";		
			break;
		case WifiManager.WIFI_STATE_ENABLING:
			result = "WIFI_STATE_ENABLING";
			break;
		case WifiManager.WIFI_STATE_DISABLING:
			result = "WIFI_STATE_DISABLING";
			break;
		default:
			result = "UNKNOWN";
			break;
		}
		
		return result;
	}
	
	public WifiConfiguration IsExsits(String SSID) 
	{
		long time1 = 0;
		long time2 = 0;
		time1 = System.currentTimeMillis();
		while (existingConfigs  == null) 
		{
			existingConfigs = wifiManager.getConfiguredNetworks();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			time2 = System.currentTimeMillis();
			if (time2 - time1 > 4*1000)
				return null;
		}

		for (WifiConfiguration existingConfig : existingConfigs) 
		{
			if (existingConfig.SSID.equals("\"" + SSID + "\"")) 
			{
				Log.i("debug.info", "existingConfig.SSID:\"" + SSID + "\""
						+ " WIFI networkID:" + existingConfig.networkId);
				return existingConfig;
			}
		}
		return null;
	}
	
	public void setWifiList(List<ScanResult> list)
	{
		wifi_list = list;
	}
	
	public void setWifiExistConfig(List<WifiConfiguration> config)
	{
		existingConfigs = config;
	}
	
	public String MacToSsid(String mac)
	{
		String ssid=null;
		if(mac != null)
		{
			if(wifi_list == null)
			{
				
				while(!wifiManager.startScan());
				wifi_list = wifiManager.getScanResults();
			}
			
			for(int i=0;i<wifi_list.size();i++)
			{
//				Log.i("debug.info","SSID " + wifi_list.get(i).SSID+" MAC:"+wifi_list.get(i).BSSID);
				if(wifi_list.get(i).BSSID.equals(mac))
				{
					ssid = wifi_list.get(i).SSID;
					Log.i("debug.info","MAC:"+wifi_list.get(i).BSSID+" To "+"SSID:"+ssid);
					break;
				}
			}
		}
		return ssid;
	}
	@SuppressLint("DefaultLocale")
	public boolean isMacValid(String mac)
	{
		mac = mac.toString();
		mac = mac.toLowerCase();
		if(!mac.isEmpty())
		{
			if(mac.matches("^[a-z0-9]{2}(:[a-z0-9]{2}){5}$"))
			{
				return true;
			}

		}
		return false;
	}

	public WifiConfiguration CreateWifiInfo(String mac, String Password) 
	{

		while (!wifiManager.disconnect());
		String SSID = MacToSsid(mac);
		if (SSID == null)
			return null;
		WifiConfiguration tempConfig = this.IsExsits(SSID);
		if (tempConfig != null) {
			wifiManager.removeNetwork(tempConfig.networkId);
		}

		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();

		config.SSID = "\"" + SSID + "\"";
		config.hiddenSSID = false;
		config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
		config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);// WPA2/IEEE 802.11i

		return config;
	}
	
	public boolean addNetwork(WifiConfiguration wcg)
	{
		if (wcg == null) {
			Log.i("debug.info", "can not match SSID.........");
			return false;
		}
		int wcgID = wifiManager.addNetwork(wcg);
		boolean b = wifiManager.enableNetwork(wcgID, true);
		if(b == false)
			return false;
		wifiManager.saveConfiguration();
		wifiManager.setWifiEnabled(true);
		old_time = SystemClock.uptimeMillis();
		Log.i("debug.info", "WIFI networkID=" + wcgID + " EnableNetwork:" + b);
		return true;
	}
	
	public  boolean getDhcp()
	{
		DhcpInfo info = wifiManager.getDhcpInfo();
		int i = 0;
		i = info.ipAddress;
		if(i != 0)
		{
			Log.i("debug.info","obtain ip:"+(i & 0xFF) + "." + 
					((i >> 8) & 0xFF) + "." +  
					((i >> 16) & 0xFF) + "." +  
					(i >> 24 & 0xFF));
			return true;
		}
		return false;
	}
	
	public int isWifiConnected(Context context) 
	{
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifiNetworkInfo = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		/*NetworkInfo wifiNetworkInfo = connectivityManager
				.getActiveNetworkInfo();*/
		if (wifiNetworkInfo != null && wifiNetworkInfo.isConnected()) {
			return 0;
		}
		long new_time = SystemClock.uptimeMillis();
		if((new_time-old_time) >= 50*1000)
		{
			Log.i("debug.info","DHCP timeout(ms):"+(new_time-old_time));
			return -1;
		}
		return 1;
	}
	
}



